<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Image Preview</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }

    .entry {
      margin-bottom: 40px;
    }

    .title {
      font-weight: bold;
      margin-bottom: 10px;
    }

    .title a {
      margin-left: 10px;
      font-size: 0.9em;
      color: blue;
      text-decoration: underline;
    }

    .images {
      display: flex;
      gap: 20px;
      flex-wrap: nowrap;
    }

    .image-block {
      text-align: center;
      width: 400px;
    }

    .image-block span {
      display: block;
      margin-bottom: 5px;
      font-size: 0.9em;
      color: #555;
    }

    .image-block img,
    .image-placeholder {
      width: 100%;
      object-fit: contain;
      border: 1px solid #ccc;
      background-color: #f0f0f0;
    }

    .image-placeholder {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
      font-size: 14px;
    }
  </style>
</head>

<body>
  <h2 id="total">Loading...</h2>
  <div id="container"></div>

  <script>
    class ImageEntryRenderer {
      constructor(container, preShowColumn) {
        this.container = container;
        this.labels = preShowColumn.sort((a, b) => a.colIdx - b.colIdx);
        this.selectedNames = new Set();
        this.entries = [];
      }

      render(entries) {
        this.entries = entries;
        this.container.innerHTML = '';

        const infoTop = this._createInfoBar();
        const infoBottom = this._createInfoBar();

        this.container.appendChild(infoTop);

        entries.forEach(entry => this._renderEntry(entry));

        this.container.appendChild(infoBottom);
        this._updateInfoBars();
      }

      _renderEntry(entry) {
        const div = document.createElement('div');
        div.className = 'entry';

        div.appendChild(this._createTitle(entry));
        div.appendChild(this._createImageRow(entry));

        this.container.appendChild(div);
      }

      _createTitle(entry) {
        const title = document.createElement('div');
        title.className = 'title';

        // 创建复选框
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.dataset.name = entry.orig_name;
        checkbox.addEventListener('change', () => {
          this._updateSelection(entry.orig_name, checkbox.checked);
        });

        // 创建名称节点
        const nameNode = document.createTextNode(` ${entry.orig_name}`);

        // 创建链接
        const viewLink = this._createLink('[View FITS]', () => {
          openFitsViewerByName(entry.orig_name);
        });

        // 组装元素
        title.appendChild(checkbox);
        title.appendChild(nameNode);
        title.appendChild(viewLink);

        return title;
      }

      _createLink(text, onClick) {
        const link = document.createElement('a');
        link.href = '#';
        link.textContent = text;
        link.style.marginLeft = '10px';
        link.addEventListener('click', onClick);
        return link;
      }

      _createImageRow(entry) {
        const row = document.createElement('div');
        row.className = 'images';

        for (const { keyName, showColumnName } of this.labels) {
          const block = document.createElement('div');
          block.className = 'image-block';

          const label = document.createElement('span');
          label.textContent = showColumnName;
          block.appendChild(label);

          if (entry[keyName]) {
            const img = document.createElement('img');
            img.src = entry[keyName];
            img.alt = keyName;
            img.onerror = () => {
              img.replaceWith(createPlaceholder('Image not found'));
            };
            block.appendChild(img);
          } else {
            block.appendChild(createPlaceholder('No image'));
          }

          row.appendChild(block);
        }

        return row;
      }

      _updateSelection(name, isSelected) {
        if (isSelected) {
          this.selectedNames.add(name);
        } else {
          this.selectedNames.delete(name);
        }
        this._updateInfoBars();
      }

      _updateInfoBars() {
        const count = this.entries.length;
        const selected = this.selectedNames.size;

        const infoBars = this.container.querySelectorAll('.info-bar');
        infoBars.forEach(bar => {
          bar.querySelector('.total-count').textContent = count;
          bar.querySelector('.selected-count').textContent = selected;
        });
      }

      _createInfoBar() {
        const bar = document.createElement('div');
        bar.className = 'info-bar';
        bar.style.margin = '10px 0';
        bar.style.fontSize = '0.95em';
        bar.style.color = '#333';

        bar.innerHTML = `
    Total: <span class="total-count">0</span> |
    Selected: <span class="selected-count">0</span>
  `;

        const btn = document.createElement('button');
        btn.textContent = 'Download Selected';
        btn.style.marginLeft = '10px';
        btn.addEventListener('click', () => this._downloadSelected());

        bar.appendChild(btn);
        return bar;
      }

      _downloadSelected() {
        const selectedArray = Array.from(this.selectedNames);
        const blob = new Blob([JSON.stringify(selectedArray, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = 'selected_orig_names.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }
    }

    function createPlaceholder(text) {
      const placeholder = document.createElement('div');
      placeholder.className = 'image-placeholder';
      placeholder.textContent = text;
      return placeholder;
    }

    function openFitsViewerByName(targetName) {
      const url = `show_fits.html?name=${encodeURIComponent(targetName)}&datasetname=${encodeURIComponent(datasetName)}`;
      window.open(url, '_blank');
    }

    function getQueryParam(param) {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get(param);
    }

    const datasetName = getQueryParam("datasetname");
    if (!datasetName) {
      document.getElementById('total').innerText = '未提供 datasetname 参数';
      throw new Error('datasetname 参数缺失');
    }

    fetch('data/datasets.json')
      .then(res => res.json())
      .then(datasetList => {
        dataset = datasetList.find(d => d.name === datasetName);
        if (!dataset) {
          document.getElementById('total').innerText = `找不到数据集：${datasetName}`;
          throw new Error('无效的 datasetname');
        }
        return fetch(dataset.dataInfo);
      })
      .then(res => res.json())
      .then(data => {
        document.getElementById('total').innerText = `Total Items: ${data.length}`;
        const renderer = new ImageEntryRenderer(document.getElementById('container'), dataset.preShowColumn);
        renderer.render(data);
      })
  </script>

  <script src="http://10.34.1.111:5066/firefly/firefly_loader.js"></script>
</body>

</html>